const path = require("path");
const express = require("express");
const db = require(path.join(__dirname, "../db"));
const router = express.Router();

// 获取所有的书籍接口
// 获取所有书籍接口
router.get("/getbooks", (req, res) => {
    let sql = "select * from student";
    db(sql, null, (err, result) => {
        if (err) console.log(err);
        res.send({
            status: 200,
            msg: "获取成功",
            data: result,
        });
    });
});

// 添加书籍接口
router.post("/addbook", (req, res) => {
    db("insert into student set ?", req.body, (err, result) => {
        if (err || result.affectedRows <= 0) {
            console.log(err);
            res.send({
                status: 500,
                msg: "添加图书失败",
            });
        } else {
            res.send({
                status: 200,
                msg: "添加图书成功",
            });
        }
    });
});

// 删除书籍接口
router.get("/delbook", (req, res) => {
    let id = req.query.id;
    db("delete from student where id=?", id, (err, result) => {
        if (err || result.affectedRows <= 0) {
            console.log(err);
            res.send({ status: 500, msg: "删除失败" });
        } else {
            res.send({
                status: 200,
                msg: "删除成功",
            });
        }
    });
});

module.exports = router;